<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Request;
use ouyangke\Ticket;
use Symfony\Component\VarDumper\Cloner\Data;

class Login
{
    // Access to XMLHttpRequest at 'http://www.tp.com/index.php/api/Api/index' 
    // from origin 'http://localhost:8080' has been blocked by CORS policy: No 
    // 'Access-Control-Allow-Origin' header is present on the requested resource.
    // 错误信息：是因为前后端分离导致的。前后端 前端和后端的域名不是一个。不是一个，就会出现这种错误。
    // 跨域名访问的安全错误提示

    public function __construct()
    {
        // 使用php的header函数，设置为*，全部能访问
        header("Access-Control-Allow-Origin:*");
    }

    public function login()
    {
        try {
            $params = input('post.');
            $user = DB::table('oyk_user')->where('phone', $params['phone'])->find();
            if (empty($user)) {
                echo '用户不存在';
                exit;
            }
            if ($user['password'] != md5($params['password'])) {
                echo '密码错误';
                exit;
            }
            unset($user['password']);
            $user['token'] = Ticket::create($user['uid'], 'ouyangke');
            return formatting([
                'code' => 1,
                'data' =>  ['user' => $user]
            ]);
        } catch (\Exception $e) {
            return formatting([
                'code' => -1,
                'error' => $e->getMessage()
            ]);
        }
    }

}
